﻿using UnityEngine;
using System.Collections.Generic;

public class InGame : MonoBehaviour 
{
	/// <summary>
	/// The background texture.
	/// </summary>
	public Texture texture;

	/// <summary>
	/// The user.
	/// </summary>
	private User user;

	/// <summary>
	/// The match.
	/// </summary>
	private Match match;

	/// <summary>
	/// The type of the match.
	/// </summary>
	private Constants.MatchTypes matchType;

	/// <summary>
	/// The card model.
	/// </summary>
	private CardModel cardModel;

	/// <summary>
	/// The state.
	/// </summary>
	private bool didSelectAnswer = false;

	/// <summary>
	/// The selected answer.
	/// </summary>
	private string selectedAnswer = string.Empty;

	/// <summary>
	/// The index of the question.
	/// </summary>
	private int questionIndex;

	private string customQuestion = string.Empty;
	private string [] customAnswers;

	private List<string> normalGameAnswers = new List<string> (8);
	private List<string> customGameAnswers = new List<string> (4);

	/// <summary>
	/// The state.
	/// </summary>
	private GUIState state;
	private enum GUIState
	{
		Deck,
		DeckPlus,
		Questions,
		Created
	}

	private DeckPlusTypeState deckPlusState;
	private enum DeckPlusTypeState
	{
		WriteAnswers,
		SelectAnswer
	}

	private QuestionsTypeState questionsState;
	private enum QuestionsTypeState
	{
		WriteQuestion,
		WriteAnswers,
		SelectAnswer
	}

	private void Start()
	{
		customAnswers = new string [4];
		for (int i = 0; i < customAnswers.Length; i++) 
		{
			customAnswers[i] = string.Empty;
		}

		user = User.Instance;

		if (PlayerPrefs.GetInt("MatchType") == Constants.MATCH_TYPE_DECK)
		{
			matchType = Constants.MatchTypes.Deck;
			state = GUIState.Deck;
		}
		else if (PlayerPrefs.GetInt("MatchType") == Constants.MATCH_TYPE_DECKPLUS)
		{
			deckPlusState = DeckPlusTypeState.WriteAnswers;
			matchType = Constants.MatchTypes.DeckPlus;
			state = GUIState.DeckPlus;
		}
		else if (PlayerPrefs.GetInt("MatchType") == Constants.MATCH_TYPE_QUESTIONS)
		{
			questionsState = QuestionsTypeState.WriteQuestion;
			matchType = Constants.MatchTypes.Questions;
			state = GUIState.Questions;
		}

		cardModel = new CardModel ();
		cardModel.FakeData ();

		question = cardModel.Questions[questionIndex];
		answers = cardModel.QuestionsAndAnswers[question];
		
		customQuestion = question;
	}
	
	private void ChooseFriends()
	{
		
	}

	bool bannerActive;
	private void ActivateBanner()
	{
		bannerActive = true;
	}
	private void ShowBanner()
	{
		if (bannerActive)
		{
			if (GUI.Button(new Rect(0,0,Screen.width,Screen.height), "BANNER"))
			{
				bannerActive = false;
			}
		}
	}

	private void CreateMatch()
	{
		if (user.Matches.Count < Constants.MAX_AMOUNT_MATCHES_TOTAL)
		{
			if (user.Matches.Count == Constants.MAX_AMOUNT_MATCHES_WITHOUT_BANNER_MIN || 
			    user.Matches.Count >= Constants.MAX_AMOUNT_MATCHES_WITHOUT_BANNER_MAX)
			{
				ActivateBanner();
			}
			
			// Poner esto en el callback del BANNER
			match = new Match(user, "Match " + user.Matches.Count, matchType);

			match.Question = customQuestion;
			match.SelectedAnswer = selectedAnswer;

			if (matchType == Constants.MatchTypes.Questions)
			{
				foreach (string s in customAnswers) {
					customGameAnswers.Add(s);
				}
				match.Answers = customGameAnswers;
			}
			else
			{
				answers[questionIndex].ForEach(a =>
				                               {
					normalGameAnswers.Add(a);
				});
				
				match.Answers = normalGameAnswers;
			}

			user.AddMatch(match);
			
			// Elegir los amigos para jugar, entre 3 y 5.
			ChooseFriends();
		}
		else
		{
			Debug.Log("NO PODES CREAR MAS DE 7 GUACHO");
		}
	}

	string question = string.Empty;
	List<List<string>> answers = new List<List<string>>();

	private void ShowDeckInfo()
	{
		GUILayout.TextField (customQuestion);

		answers[questionIndex].ForEach (a => 
		{
			if (GUILayout.Button (a))
			{
				didSelectAnswer = true;
				selectedAnswer = a;
			}
		});

		if (GUILayout.Button("Volver"))
		{
			Application.LoadLevel(Constants.SCENE_MAIN);
		}
	}

	private void DeckPlusFlow()
	{
		switch (deckPlusState) 
		{
			case DeckPlusTypeState.WriteAnswers:
				DeckPlusWriteAnswersState();
				break;
			case DeckPlusTypeState.SelectAnswer:
				DeckPlusSelectAnswerState();
				break;
			default: 
				DeckPlusWriteAnswersState();
				break;
		}
	}
	
	private void DeckPlusWriteAnswersState()
	{		
		ChangeQuestion ();

		GUILayout.TextField (customQuestion);

		GUILayout.TextArea ("Agrega las Respuestas");

		customAnswers[0] = GUILayout.TextField(customAnswers[0]);

		customAnswers[1] = GUILayout.TextField(customAnswers[1]);

		if (GUILayout.Button ("Aceptar"))
		{
			tmpList = answers[questionIndex];
			tmpList[0] = customAnswers[0];
			tmpList[1] = customAnswers[1];
			deckPlusState = DeckPlusTypeState.SelectAnswer;
		}		

		if (GUILayout.Button("Volver"))
		{
			Application.LoadLevel(Constants.SCENE_MAIN);
		}
	}
	
	List<string> tmpList;
	private void DeckPlusSelectAnswerState()
	{		
		GUILayout.TextArea (customQuestion);
		GUILayout.TextArea ("Seleccione Respuesta");

		for (int i = 0; i < tmpList.Count; i++)
		{
			if (GUILayout.Button (tmpList[i]))
			{
				didSelectAnswer = true;
				selectedAnswer = tmpList[i];
			}
		}		

		if (GUILayout.Button("Volver"))
		{
			didSelectAnswer = false;
			selectedAnswer = string.Empty;
			deckPlusState = DeckPlusTypeState.WriteAnswers;
		}
	}

	private void DeckState()
	{
		// Obtener una pregunta del servidor
		ShowDeckInfo ();

		// Mostrar todas las respuestas
	}

	private void DeckPlusState()
	{
		// Obtener una pregunta del servidor
		DeckPlusFlow ();

		// Mostrar las demas respuestas
	}

	private void CreateFullyCustomDataFlow()
	{
		switch (questionsState) 
		{
			case QuestionsTypeState.WriteQuestion:
				QuestionWriteQuestionState();
				break;
			case QuestionsTypeState.WriteAnswers:
				QuestionWriteAnswersState();
				break;
			case QuestionsTypeState.SelectAnswer:
				QuestionSelectAnswerState();
				break;
			default: 
				QuestionWriteQuestionState();
				break;
		}
	}
	
	private void QuestionWriteQuestionState()
	{
		// Insertar pregunta
		GUILayout.TextArea ("Escribi la Pregunta");
		customQuestion = GUILayout.TextField (customQuestion);
		
		if (GUILayout.Button("Aceptar"))
		{
			questionsState = QuestionsTypeState.WriteAnswers;
			if (tmpList == null)
				tmpList = new List<string>();
		}
		if (GUILayout.Button("Volver"))
		{
			Application.LoadLevel(Constants.SCENE_MAIN);
		}
	}

	private void QuestionWriteAnswersState()
	{
		GUILayout.TextArea (customQuestion);
		// Insertar Respuestas
		GUILayout.TextArea ("Escriba las Respuestas");
		for (int i = 0; i < customAnswers.Length; i++) 
		{
			customAnswers[i] = GUILayout.TextField(customAnswers[i]);
		}

		if (GUILayout.Button("Aceptar"))
		{		
			tmpList.Clear();
			for (int i = 0; i < customAnswers.Length; i++) 
			{
				tmpList.Add(customAnswers[i]);
			}
			questionsState = QuestionsTypeState.SelectAnswer;
		}
		if (GUILayout.Button("Volver"))
		{
			questionsState = QuestionsTypeState.WriteQuestion;
		}
	}
	
	private void QuestionSelectAnswerState()
	{
		GUILayout.TextArea (customQuestion);
		GUILayout.TextArea ("Seleccione Respuesta");
		
		for (int i = 0; i < tmpList.Count; i++)
		{
			if (GUILayout.Button (tmpList[i]))
			{
				didSelectAnswer = true;
				selectedAnswer = tmpList[i];
			}
		}		
		
		if (GUILayout.Button("Volver"))
		{
			didSelectAnswer = false;
			selectedAnswer = string.Empty;
			questionsState = QuestionsTypeState.WriteAnswers;
		}
	}

	private void QuestionsState()
	{
		CreateFullyCustomDataFlow ();
	}

	private void Created()
	{
		GUILayout.TextArea("Partida Creada!\nEncontras tu partida en Partidas Creadas");
		
		if (GUILayout.Button("Volver"))
		{
			Application.LoadLevel(Constants.SCENE_MAIN);
		}
	}

	private void AnswerSelected()
	{		
		if (didSelectAnswer)
		{
			GUILayout.TextArea("Usted selecciono: " + selectedAnswer);
			if (GUILayout.Button("Empezar Partida!"))
			{
				CreateMatch();
				state = GUIState.Created;
			}
		}
	}

	private void ChangeQuestion()
	{
		for (int i = 0; i < Constants.MAX_QUESTIONS_FREE_VERSION; i++)
		{
			if (questionIndex != i)
			{
				if (GUILayout.Button("Pregunta Opcion " + (i+1).ToString()))
				{
					didSelectAnswer = false;
					selectedAnswer = string.Empty;
					questionIndex = i;

					question = cardModel.Questions[questionIndex];
					//answers = cardModel.QuestionsAndAnswers[question];
					
					customQuestion = question;

					ActivateBanner ();
				}
			}
		}
	}

	private void OnGUI()
	{
		GUI.DrawTexture(new Rect(0f, 0f, Screen.width, Screen.height), texture);

		switch (state)
		{
			case GUIState.Deck:
			{
				ChangeQuestion ();

				DeckState();
				
				AnswerSelected();

				break;
			}

			case GUIState.DeckPlus:
			{
				DeckPlusState();
				
				AnswerSelected();

				break;
			}
				
			case GUIState.Questions:
			{
				QuestionsState();
				
				AnswerSelected();
				
				break;
			}
				
			case GUIState.Created:
			{
				Created();
				break;
			}

			default:
			{
				DeckState();
				break;
			}
		}

		ShowBanner();
	}
}
